package com.yzy.baselibrary.base.viewmodel

import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel

/**
 *description: 带生命周期管理的ViewModel基类.
 *@date 2018/10/15 16:25.
 *@author: YinZeYu.
 */
open class LifecycleViewModel : ViewModel(), IViewModel {

  var lifecycleOwner: LifecycleOwner? = null

  @CallSuper
  override fun onCreate(lifecycleOwner: LifecycleOwner) {
    this.lifecycleOwner = lifecycleOwner
  }

  @CallSuper
  override fun onStart(lifecycleOwner: LifecycleOwner) {

  }

  @CallSuper
  override fun onResume(lifecycleOwner: LifecycleOwner) {

  }

  @CallSuper
  override fun onPause(lifecycleOwner: LifecycleOwner) {

  }

  @CallSuper
  override fun onStop(lifecycleOwner: LifecycleOwner) {

  }

  @CallSuper
  override fun onDestroy(lifecycleOwner: LifecycleOwner) {
    this.lifecycleOwner = null
  }

  @CallSuper
  override fun onLifecycleChanged(lifecycleOwner: LifecycleOwner,
                                  event: Lifecycle.Event) {

  }

  fun addLifecycle(activity: FragmentActivity) {
    activity.lifecycle.addObserver(this)
  }

  fun addLifecycle(fragment: Fragment) {
    fragment.lifecycle.addObserver(this)
  }
}